#include<errno.h>
#include<pthread.h>
#include<stdio.h>
#include<string.h>
#include <unistd.h>
#include"platform.h"
#include"mosquitto.h"
#include "client_pthread.h"
/*
typedef struct
{
       int                       detachstate;   // 线程的分离状态
       int                       schedpolicy;   // 线程调度策略
       structsched_param         schedparam;    // 线程的调度参数
       int                       inheritsched;  // 线程的继承性
       int                       scope;         // 线程的作用域
       size_t                    guardsize;     // 线程栈末尾的警戒缓冲区大小
       int                       stackaddr_set; // 线程的栈设置
       void*                     stackaddr;     // 线程栈的位置
       size_t                    stacksize;     // 线程栈的大小
} pthread_attr_t;
*/


int thread_init(pthread_t *tid,thread_worker* thread_work,void *args){


        msq_ctx_t       *msq=(msq_ctx_t *)args;
        pthread_attr_t  attr;
        int             rv=-1;
        //if(!msq){
        //      printf("pthread create failure:%s\n",strerror(errno));
        //      return 0;
        //}
        if(pthread_attr_init(&attr)){
                printf("pthread_attr_init failure:%s\n",strerror(errno));
                pthread_attr_destroy(&attr);
                return 0;
        }
        printf("pthread_attr_init");
        if(pthread_attr_setstacksize(&attr,120*1024)){
                printf("pthread_attr_setstacksize failure:%s\n",strerror(errno));
                pthread_attr_destroy(&attr);
                goto cleanup;
        }
        printf("pthread_attr_setstacksize success\n");
        if(pthread_attr_setdetachstate(&attr,PTHREAD_CREATE_DETACHED)){
                printf("pthread_attr_setdetachstate failure:%s\n",strerror(errno));
                pthread_attr_destroy(&attr);
                goto cleanup;
        }
        printf("pthread_attr_setdetachstate success\n");
        rv=pthread_create(tid,&attr,thread_work,msq);
        if(rv)
                goto cleanup;



cleanup:
        pthread_attr_destroy(&attr);
        return 0;

}
void *thread_work(void * args)
{

        msq_ctx_t       *msq=(msq_ctx_t *)args;
        int             rv=-1;

        while(!sig_stop)
        {
                if((mosquitto_connect(msq->p_ctx.mosq,msq->p_ctx.get_ip,msq->p_ctx.port,msq->p_ctx.keepalive))==MOSQ_ERR_SUCCESS)
                {
                        printf("connect ok\n");
                        connect_flag=1;
                }
                else{
                        printf("The connection was lost after obtaining data\n");
                        connect_flag=0;
                }
                printf("connect_flag=%d\n",connect_flag);
                sleep(3);
        }
}

